import json
from collections import OrderedDict

from django import http
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
from django.urls import reverse

from django.views import View
from django_redis import get_redis_connection

from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories
from apps.goods.models import GoodsChannel
from apps.goods.utils import CookieSecret
from apps.users.models import User
from meiduo_test.settings.dev import logger
from utils.response_code import RETCODE




class LoginView(View):
    def get(self,request):
        return render(request,'login.html')
    def post(self,request):
        #1.校验
        cookies_data = request.COOKIES.get('carts')
        response = redirect(reverse('contents:index'))
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        user = authenticate(username=username, password=password)
        print('*'*10,user)
        if not user:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        if cookies_data is not None:
            cookies_data = CookieSecret.loads(cookies_data)

            redis_client=get_redis_connection('carts')
            redis_data=redis_client.hgetall('carts_%d' %user.id)
            data_dict={}

            for keys,value in redis_data.items():
                    sku_id=int(keys.decode())
                    values=json.loads(value.decode())
                    print(values)
                    data_dict[sku_id]=values


            for key in cookies_data:
                data_dict[key]=cookies_data[key]

            for key in data_dict:
                redis_client.hset('carts_%d' % user.id,key,json.dumps(data_dict[key]))

        #2.保持登录状态
        login(request,user)
        #3设置session过期时间

        if remembered=="on":
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)
        # 响应登录结果

        response.delete_cookie('carts')
        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class LogoutView(View):
    def get(self,request):
        logout(request)
        response=redirect(reverse('contents:index'))
        response.delete_cookie('username')

        return response

class UserInfoView(LoginRequiredMixin,View):
    #获得用户中心页面
    def get(self,request):
        context={
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active
        }
        return render(request, 'user_center_info.html',context)

class EmailView(LoginRequiredMixin,View):
    def put(self,request):
        #获取邮箱地址
        email=(json.loads(request.body.decode()))['email']

        #数据库设置该邮箱
        try:
            request.user.email=email
            request.user.save()
        except:


            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})
        #如未绑定，则发送邮箱验证码验证码进行校验
        #发送邮件
        #进行校验
        #成功后更改用户的邮箱,更改邮箱激活状态
        # 4.异步发送邮件
        verify_url = 'http://www.meiduo.site:8000/emails/verification?'


        verify_url=verify_url+'user_id='+str(request.user.id)+'&email='+request.user.email
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})

class VerifyEmailView(View):
    def get(self,request):


        user_id=request.GET.get('user_id')
        email=request.GET.get('email')
        try:
            request.user.email_active=True
            request.user.save()
        except:
            return http.HttpResponseForbidden

        # return http.HttpResponse('成功')

        return redirect(reverse('users:info'))

#修改密码
class UpdatepwdView(View):
    def get(self,request):
        return render(request,'user_center_pass.html')

    def post(self,request):
        old_pwd=request.POST.get('old_pwd')
        new_pwd=request.POST.get('new_pwd')
        new_cpwd=request.POST.get('new_cpwd')

        result=request.user.check_password(old_pwd)

        if not result:

            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'})


        request.user.set_password(new_pwd)
        request.user.save()

        logout(request)
        response = redirect(reverse('contents:login'))
        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response

class IndexView(View):
    def get(self,request):
        contents={}
        content_categories=ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key]=cat.content_set.all()
        context={
            'categories':get_categories(),
            'contents':contents
        }

        return render(request,'index.html',context)


